package com.ay.weixin.fdc.front.kanfang.event;

import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;

import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.intercepter.Before;
import org.lizar.controller.loader.BasicLoader;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.util.StringHelper;

import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.types.FDCProjectStatus;
import com.ay.weixin.config.types.KanFangProgress;
import com.ay.weixin.config.types.KanFangStatus;
import com.ay.weixin.config.types.KanFangType;
import com.ay.weixin.config.types.UserStatus;
import com.ay.weixin.fdc.admin.category.domain.CategoryLoader;
import com.ay.weixin.fdc.boss.kanfang.db.IbatisKanFangDao;
import com.ay.weixin.fdc.boss.kanfang.db.IbatisKanFangFlowDao;
import com.ay.weixin.fdc.boss.kanfang.domain.KanFang;
import com.ay.weixin.fdc.boss.kanfang.domain.KanFangFlow;
import com.ay.weixin.fdc.boss.kanfang.event.KanFangMC;
import com.ay.weixin.fdc.boss.project.db.IbatisProjectDao;
import com.ay.weixin.fdc.boss.project.domain.FDCProject;
import com.ay.weixin.fdc.boss.user.db.FDCAgentDao;
import com.ay.weixin.fdc.boss.user.db.WeiXinInfoDao;
import com.ay.weixin.fdc.boss.user.domain.Activity;
import com.ay.weixin.fdc.boss.user.domain.FDCAgent;
import com.ay.weixin.fdc.boss.user.domain.UserBasic;
import com.ay.weixin.fdc.boss.user.domain.UserWeiXinInfo;
import com.ay.weixin.fdc.boss.yongjin.db.IbatisCashFlow;
import com.ay.weixin.fdc.boss.yongjin.domain.CashFlow;
import com.ay.weixin.fdc.front.usercenter.event.UserInfoAccess;

public class Recommand extends Event implements Before {
	private IbatisProjectDao		project_dao;
	private IbatisKanFangDao		kanfang_dao;
	private IbatisKanFangFlowDao	flow_dao;
	private FDCAgentDao				user_dao;
	private static IbatisCashFlow	cash_dao;
	private UserInfoAccess			user_access;
	private CategoryLoader			cl;
	private KanFangEvent			kanfangEvent;
	private static WeiXinInfoDao	weixin_dao;
	
	@Override
	public void init_property() throws Exception {
		
		project_dao = Container.get(IbatisProjectDao.class);
		kanfang_dao = Container.get(IbatisKanFangDao.class);
		user_access = Container.get(UserInfoAccess.class);
		flow_dao = Container.get(IbatisKanFangFlowDao.class);
		user_dao = Container.get(FDCAgentDao.class);
		cash_dao = Container.get(IbatisCashFlow.class);
		kanfangEvent = Container.get(KanFangEvent.class);
		cl = Container.get(CategoryLoader.class);
		weixin_dao = Container.get(WeiXinInfoDao.class);
		
	}
	
	@Override
	public String default_handling_path() {
		return "/fdc/recommand/*";
	}
	
	@Override
	public void handle(EventLoader el) throws ServletException, IOException {
		long wxproject_id = el.queryPathInt(2);
		
		if (!el.getBool("is_weixin") && ProjectConfig._bool(wxproject_id,"sys.weixin_only")) {
			el.text("invalid visit");
			return;
		}
		
		UserBasic user = el.getSessionAttr("user", UserBasic.class);
		if (user == null) {
			el.response_to_root("/fdc/login/" + wxproject_id);
			return;
		}
		UserWeiXinInfo weixin_info = el.getSessionAttr("weixin_info", UserWeiXinInfo.class);
		if (weixin_info == null) {
			user_access.open_id_check(el, "/fdc/recommand/", wxproject_id);
			return;
		}
		if (el.queryPathCheck(3, "")) {
			view(el, wxproject_id);
		} else if (el.queryPathCheck(3, "submit")) {
			submit(el, wxproject_id);
		} else if (el.queryPathCheck(3, "myRecommandList")) {
			myRecommandList(el, wxproject_id);
		} else if (el.queryPathCheck(3, "visit")) {
			visit(el, wxproject_id);
		} else if (el.queryPathCheck(3, "mySalesList")) {
			mySalesList(el, wxproject_id);
		} else if (el.queryPathCheck(3, "update_status")) {
			update_status(el, wxproject_id);
		}
	}
	
	private void update_status(EventLoader el, long wxproject_id) throws IOException, ServletException {
		long kanfang_id = el.getLong("id");
		int status = el.getInt("status");
		FDCAgent user = el.getSessionAttr("user", FDCAgent.class);
		if (!StringHelper.equals(user.getType(), "salesman")) {
			el.setAttr("msg", "权限不足");
			visit(el, wxproject_id);
			return;
		}
		if (!StringHelper.equals(user.getStatus(), "ok")) {
			el.setAttr("msg", "用户状态异常，无法操作");
			visit(el, wxproject_id);
			return;
		}
		KanFang kanfang = null;
		try {
			kanfang = kanfang_dao.get(kanfang_id);
			if (kanfang == null) {
				el.setAttr("msg", el.i18("mc.kanfang.not.exists"));
				visit(el, wxproject_id);
				return;
			}
		} catch (SQLException e) {
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			e.printStackTrace();
			visit(el, wxproject_id);
			return;
		}
		kanfang.setStatus(status);
		String status_desc = KanFangStatus.getDesc(status);
		if (status_desc == null) {
			el.setAttr("msg", "状态不正确");
			visit(el, wxproject_id);
			return;
		}
		String reason = "[销售状态更新]";
		
		String remark_append = "[" + Calendar.getInstance().getTime().toLocaleString() + "][状态更新=>" + status_desc + "] " + reason + " <br/>" + kanfang.getRemark_append();
		
		kanfang.setRemark_append(remark_append);
		
		if (status == KanFangStatus.sign_success.getValue() || status == KanFangStatus.failed_close.getValue() || status ==KanFangStatus.black_list.getValue()) {
			kanfang.setProgress(KanFangProgress.CLOSED.getValue());
		} else if (status == KanFangStatus.ready_to_sign.getValue()) {
			kanfang.setProgress(KanFangProgress.PROGRESS.getValue());
		} else {
			kanfang.setProgress(KanFangProgress.PROGRESS.getValue());
		}
		
		try {
			kanfang_dao.update(kanfang);
		} catch (SQLException e) {
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			visit(el, wxproject_id);
			return;
		}
		
		String msg = KanFangMC.insertFlow(el, kanfang_id, reason, status,user.getId());
		if (StringHelper.isNotNull(msg)) {
			el.setAttr("msg", msg);
			visit(el, wxproject_id);
			return;
		}
		
		FDCProject project = null;
		try {
			project = project_dao.get(kanfang.getProject_id());
		} catch (SQLException e) {
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			e.printStackTrace();
			visit(el, wxproject_id);
			return;
		}
		
		UserWeiXinInfo salesmanWeixinInfo = el.getSessionAttr("weixin_info", UserWeiXinInfo.class);
		UserWeiXinInfo user_weixin = null;
		try {
			user_weixin = weixin_dao.getByUserId(kanfang.getRecommend_user());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			visit(el, wxproject_id);
			return;
		}
		if (user_weixin != null && project != null) {
			
			//通知经纪人
			KanFangMC.change_status_reply(wxproject_id,"客户最新状态:" + kanfang.getStatusDesc(), user_weixin.getId(), project, kanfang, reason + "\n如有疑问,请致电客服.");
			
			if(!StringHelper.equals(user_weixin.getId(), salesmanWeixinInfo.getId())){
				//通知销售人员
				KanFangMC.change_status_reply(wxproject_id,"客户最新状态:" + kanfang.getStatusDesc(), salesmanWeixinInfo.getId(), project, kanfang, reason + "\n如有疑问,请致电客服.");
			}
		}
		
		try {
			if (status == KanFangStatus.ready_to_sign.getValue() && kanfang.getOn_visit_paid() == KanFang.ON_VISIT_NOT_PAID) {
				el.setAttr("msg", KanFangMC.offerOnvisitCash(el,wxproject_id, kanfang, project, ProjectConfig.getStr(wxproject_id,"fdc_kanfang.recommand_onvisit")));
			} else if (status == KanFangStatus.black_list.getValue()) {
				user_dao.imcreate_black_list(kanfang.getRecommend_user());
			}
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			visit(el,wxproject_id);
			return;
		}
		visit(el, wxproject_id);
	}
	
	private void visit(EventLoader el, long wxproject_id) throws IOException, ServletException {
		long kanfang_id = el.getLong("id");
		List<KanFangFlow> kflow = null;
		KanFang kanfang = null;
		FDCProject project = null;
		try {
			kanfang = kanfang_dao.get(kanfang_id);
			if (kanfang == null) {
				view(el, wxproject_id);
				return;
			}
			kflow = flow_dao.getFlow(kanfang_id);
			project = project_dao.get(kanfang.getProject_id());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		el.setAttr("project", project);
		el.setAttr("kanfang", kanfang);
		el.setAttr("kflow", kflow);
		el.setAttr("kanfang_id", kanfang_id);
		
		
		el.template("/WEB-INF/template/app/" + wxproject_id + "/fdc/kanfang/flow.vm");
	}
	
	private void submit(EventLoader el, long wxproject_id) throws IOException, ServletException {
		
		FDCAgent user = el.getSessionAttr("user", FDCAgent.class);
		
		UserWeiXinInfo weixin_info = el.getSessionAttr("weixin_info", UserWeiXinInfo.class);
		
		if (!StringHelper.equals(user.getStatus(), "ok")) {
			try {
				user = user_dao.getById(user.getId());
				el.setSessionAttr("user", user);
			} catch (SQLException e) {
				el.setAttr("msg", el.i18("fdc_project.db.error"));
				view(el, wxproject_id);
				return;
			}
			el.setSessionAttr("user", user);
			if (!StringHelper.equals(user.getStatus(), "ok")) {
				el.setAttr("msg", String.format(el.i18("usercenter.status.isabnormal"),UserStatus.getByName(user.getStatus()).getDesc()));
				view(el, wxproject_id);
				return;
			}
		}
		if (user.getBlack_list_times() >= ProjectConfig.getInt(wxproject_id,"fdc_kanfang.user_black_list_limit")) {
			el.setAttr("msg", String.format(el.i18("usercenter.status.isabnormal"), "黑名单"));
			view(el, wxproject_id);
			return;
		}
		
		String check_result = KanFangEvent.check_user_recommand_number(wxproject_id,user);
		if (check_result != null) {
			el.setAttr("msg", String.format(el.i18("fdc_project.kanfang.recommand.exceed"), ProjectConfig.getInt(wxproject_id,"fdc_kanfang.max_recommand_submit")));
			view(el, wxproject_id);
			return;
		}
		String name = el.getStr("name");
		String sex = el.getStr("sex");
		String contact = el.getStr("contact");
		String gohousedate = el.getStr("gohousedate");
		String birthday = el.getStr("birthday");
		String buyexper = el.getStr("buyexper");
		long project_id = el.getLong("project_id");
		String remark = el.getStr("remark");
		String msg = null;
		if (remark.length() > Keys.getInt("fdc_kanfang.remark_max_length")) {
			msg = String.format(el.i18("fdc_remark.max.length.exceed"), Keys.getInt("fdc_kanfang.remark_max_length"));
			el.setAttr("msg", msg);
			view(el, wxproject_id);
			return;
		}
		
		if (StringHelper.isNull(contact)) {
			msg = el.i18("fdc_project.contact.not.empty");
			el.setAttr("msg", msg);
			view(el, wxproject_id);
			return;
		}
		
		if (StringHelper.isNull(name)) {
			msg = el.i18("fdc_project.name.not.empty");
			el.setAttr("msg", msg);
			view(el, wxproject_id);
			return;
		}
		
		if (name.length() > Keys.getInt("fdc_usercenter.register_name_max_length") || name.length() < Keys.getInt("fdc_usercenter.register_name_min_length")) {
			msg = String.format(el.i18("fdc_usercenter.name.not.valid"), Keys.getInt("fdc_usercenter.register_name_min_length"), Keys.getInt("fdc_usercenter.register_name_max_length"));
			el.setAttr("msg", msg);
			view(el, wxproject_id);
			return;
		}
		
		if (!StringHelper.isLong(contact)) {
			msg = String.format(el.i18("fdc_usercenter.phone.not.valid"), Keys.getInt("fdc_usercenter.register_phone_length"));
			el.setAttr("msg", msg);
			view(el, wxproject_id);
			return;
		}
		FDCProject project = null;
		try {
			project = project_dao.get(project_id);
			if (project == null) {
				el.setAttr("msg", el.i18("fdc_project.please.select.project"));
				view(el, wxproject_id);
				return;
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
			view(el, wxproject_id);
			return;
		}
		
		KanFang kanfang = null;
		try {
			if (kanfang_dao.hasLogged(wxproject_id,contact, project_id)) {
				el.setAttr("msg", el.i18("fdc_project.kanfang.already.recommand"));
				view(el, wxproject_id);
				return;
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
			view(el, wxproject_id);
			return;
		}
		
		kanfang = new KanFang();
		kanfang.setName(name);
		kanfang.setSex(sex);
		kanfang.setBuyexper(buyexper);
		kanfang.setContact(contact);
		kanfang.setProject_id(project_id);
		kanfang.setRemark(remark);
		kanfang.setType(KanFangType.RECOMMAND.getValue());
		kanfang.setProgress(KanFangProgress.START.getValue());
		kanfang.setUpdate_date(new Date(System.currentTimeMillis()));
		kanfang.setStatus(KanFang.STATUS_NONE);
		kanfang.setCreate_time(new Date(System.currentTimeMillis()));
		kanfang.setSalesman(el.getLong("salesman"));
		if (user != null) {
			kanfang.setRecommend_user(user.getId());
			user.inc_recommand_num();
			try {
				user_dao.update(user);
			} catch (SQLException e) {
				e.printStackTrace();
				el.setAttr("msg", el.i18("fdc_project.db.error"));
				view(el, wxproject_id);
				return;
			}
		}
		
		try {
			if (StringHelper.isNotNull(birthday)) {
				kanfang.setBirthday(new SimpleDateFormat("dd/mm/yyyy").parse(birthday));
			}
			if (StringHelper.isNotNull(gohousedate)) {
				kanfang.setGohousedate(gohousedate);
			}
		} catch (ParseException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
			view(el, wxproject_id);
			return;
		}
		try {
			kanfang_dao.insert(kanfang);
			kanfang = kanfang_dao.getLastBook(wxproject_id,contact);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
			view(el, wxproject_id);
			return;
		}
		
		KanFangFlow flow = new KanFangFlow();
		flow.setCurrent_status(kanfang.getStatus());
		flow.setOper_timestamp(System.currentTimeMillis());
		flow.setKf_id(kanfang.getId());
		flow.setOper(0);
		try {
			flow_dao.insert(flow);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
			view(el, wxproject_id);
			return;
		}
		
		recommand_income(el,wxproject_id, user);
		
		
		
		try{
			recommandNotify(el,wxproject_id,weixin_info,name,project,user,contact,kanfang);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("mc.kanfang.internal.server.error") + ":" + e.getLocalizedMessage());
			visit(el,wxproject_id);
			return;
		}
		
		
		
		kanfangEvent.sendEmail(wxproject_id,project, kanfang, el);
		el.setAttr("left", ProjectConfig.getInt(wxproject_id,"fdc_kanfang.max_recommand_submit") - user.getToday_recommand_num());
		el.setAttr("msg", el.i18("fdc_project.recommand.success"));
		el.template("/WEB-INF/template/app/" + wxproject_id + "/fdc/kanfang/recommand_result.vm");
	}
	
	private void recommandNotify(EventLoader el,long wxproject_id,UserWeiXinInfo weixin_info,String name,FDCProject project,FDCAgent user,String contact,KanFang kanfang) throws SQLException {
		if (el.getLong("salesman") != 0l) {
			
			if (user.getId() == el.getLong("salesman")) {
				KanFangEvent.reply(wxproject_id,weixin_info.getId(), name, project, new SimpleDateFormat("yyyy-MM-dd").format(new Date()), contact, "已通分配销售:" + user.getName());
			} else {
				UserWeiXinInfo salesmanWeixinInfo = weixin_dao.getByUserId(el.getLong("salesman"));
				
				KanFangEvent.reply(wxproject_id,weixin_info.getId(), name, project,new SimpleDateFormat("yyyy-MM-dd").format(new Date()) , contact, "已通分配销售:" + salesmanWeixinInfo.getNickname());
				
				//通知销售人员
				KanFangEvent.reply(wxproject_id,salesmanWeixinInfo.getId(), name, project,new SimpleDateFormat("yyyy-MM-dd").format(new Date()) , contact, "已分配给您");
			}
		} else {
			KanFangEvent.reply(wxproject_id,weixin_info.getId(), name, project, "待定", contact, "");
		}
	}
	
	public static void recommand_income(EventLoader el,long wxrpoject_id, FDCAgent user) {
		float recommand_value = 0;
		if (ProjectConfig._bool(wxrpoject_id,"fdc_kanfang.income_for_recommand")) {
			if (ProjectConfig._bool(wxrpoject_id,"fdc_kanfang.recommand_confirm_benifit")) {
				recommand_value = ProjectConfig.getFloat(wxrpoject_id,"fdc_kanfang.recommand_benifit_value");
			} else {
				String result = Activity.activity_cash_rules(ProjectConfig.getStr(wxrpoject_id,"fdc_kanfang.recommand_invite_benifit_rules"));
				try {
					recommand_value = Float.parseFloat(result);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (recommand_value > 0) {
				CashFlow mycash = new CashFlow();
				mycash.setCash(recommand_value);
				mycash.setFrom_user_id(0);
				mycash.setReason(ProjectConfig.getStr(wxrpoject_id,"fdc_kanfang.recommand_return"));
				mycash.setTimestamp(System.currentTimeMillis());
				mycash.setUser_id(user.getId());
				mycash.setFlow_in(CashFlow.FLOW_IN);
				mycash.setIn_status(CashFlow.IN_STATUS_IN);
				try {
					cash_dao.insert(mycash);
				} catch (SQLException e) {
					e.printStackTrace();
				}
				el.setAttr("cash", mycash);
			}
			
		}
	}
	
	private void view(EventLoader el, long wxproject_id) throws IOException, ServletException {
		long project_id = el.getLong("id");
		
		List<FDCProject> plist = null;
		List<FDCAgent> salesman = null;
		try {
			plist = project_dao.getAllByFront(wxproject_id,FDCProjectStatus.onsale.getCode());
			salesman = user_dao.getAllSalesmanByStatus(wxproject_id,"ok");
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
		}
		
		el.setAttr("salesList", salesman);
		el.setAttr("project_list", plist);
		el.setAttr("id", project_id);
		el.template("/WEB-INF/template/app/" + wxproject_id + "/fdc/kanfang/recommand.vm");
	}
	
	private void myRecommandList(EventLoader el, long wxproject_id) throws IOException, ServletException {
		List<FDCProject> plist = null;
		try {
			plist = project_dao.getAllByFront(wxproject_id,FDCProjectStatus.onsale.getCode());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
		}
		el.setAttr("project_list", plist);
		FDCAgent user = el.getSessionAttr("user", FDCAgent.class);
		List<KanFang> rlist = null;
		
		try {
			rlist = kanfang_dao.getRecommandList(user.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
		}
		
		el.setAttr("rlist", rlist);
		el.template("/WEB-INF/template/app/" + wxproject_id + "/fdc/kanfang/list.vm");
	}
	
	private void mySalesList(EventLoader el, long wxproject_id) throws IOException, ServletException {
		List<FDCProject> plist = null;
		try {
			plist = project_dao.getAllByFront(wxproject_id,FDCProjectStatus.onsale.getCode());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
		}
		el.setAttr("project_list", plist);
		FDCAgent user = el.getSessionAttr("user", FDCAgent.class);
		List<KanFang> rlist = null;
		
		try {
			rlist = kanfang_dao.getSalesList(user.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_project.db.error"));
		}
		
		el.setAttr("rlist", rlist);
		
		
		el.template("/WEB-INF/template/app/" + wxproject_id + "/fdc/kanfang/list.vm");
	}
	
	@Override
	public void before(BasicLoader bl) throws ServletException, IOException {
		long wxproject_id=bl.queryPathInt(2);
		bl.setAttr("mc_user_enable_salesman", ProjectConfig.getBool(wxproject_id,"fdc_usercenter.enable_salesman"));
	}
	
}
